<?php

namespace app\app\controller;
use think\Db;

class User extends Common
{
    //获取个人信息
    public function get_info()
    {
        $uid = token_decode(req('token'));
        $state = 1;
        $data = json('');
        if (!$uid) {
            $state = 0;
            $msg = '请登录后查看！';
        }else{
            $data = Db::table('user')->field('phone,headimg,name')->where('id', $uid)->find();
			if(empty($data['name'])){
				$data['name'] = $data['phone'];
			}
			if(empty($data['headimg'])){
				$data['headimg'] = "http://ozwioy5e5.bkt.clouddn.com/default_head.jpg";
			}
            $msg = '获取成功';
        }
        return json(['state' => $state, 'data' => $data, 'msg' => $msg]);
    }

    //编辑个人信息
    public function set_info()
    {
        $uid = token_decode(req('token'));
        $data = [];
        $msg['state'] = 0;
        $msg['data'] = '';
        $name = req('name');
        if (empty($uid)) {
            $msg['msg'] = '请先登录';
        } else {
            if (empty($name) && !$_FILES) {
                $msg['msg'] = '参数错误';
            } else {
                if (!empty($name)) {
                    $data['name'] = $name;
                }
                if ($_FILES) {
                    $headimg = upload();
                    $data['headimg'] = $headimg['headimg']['url'];
                }
                Db::table('user')->where('id', $uid)->update($data);
                $msg['state'] = 1;
                $msg['msg'] = '修改成功';
            }
        }
        return json($msg);
    }

    //获取地址列表
    public function address_list()
    {
        $uid = token_decode(req('token'));
        $msg['state'] = 0;
        $msg['data'] = [];
        if (empty($uid)) {
            $msg['msg'] = '请先登录后再查看';
        } else {
            $msg['data'] = Db::table('address')->field('id as address_id,label,phone,name,sex,address_title,address_content,address_detail,lng,lat,def')->where('uid', $uid)->order('def desc')->select();
            $msg['state'] = 1;
            $msg['msg'] = '获取成功';
        }
        return json($msg);
    }

    //设置默认地址
    public function set_def_address()
    {
        $uid = token_decode(req('token'));
        $address_id = req('address_id');
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($uid) || empty($address_id)) {
            $msg['msg'] = '参数错误';
        } else {
            $msg['state'] = 1;
            Db::table('address')->where(['uid' => $uid])->update(['def' => 0]);
            Db::table('address')->where(['uid' => $uid, 'id' => $address_id])->update(['def' => 1]);
            $msg['msg'] = '操作成功';
        }
        return json($msg);
    }

    //编辑地址
    public function edit_address()
    {
        $uid = token_decode(req('token'));
        $address_id = req('address_id');
        $lng = req('lng');
        $lat = req('lat');
        $msg['state'] = 0;
        $msg['data'] = '';
        $data = [];
        if (empty($uid)) {
            $msg['msg'] = '参数错误';
        } else {
            $data['uid'] = $uid;
            $data['lng'] = $lng;
            $data['lat'] = $lat;
            $data['label'] = (string)req('label');
            $data['name'] = (string)req('name');
            $data['phone'] = (string)req('phone');
            $data['address_title'] = (string)req('address_title');
            $data['address_content'] = (string)req('address_content');
            $data['address_detail'] = (string)req('address_detail');
            $def = (int)req('def');
            $data['sex'] = (string)req('sex');
            if ($address_id == '') {
                $bool = true;
                foreach ($data as $k => $v) {
                    if ($v == '' && $k != 'sex' && $k != 'label' && $k != 'address_detail') {
                        $bool = false;
                        $msg['msg'] = '参数错误';
                        break;
                    }
                }
                if ($bool) {
                    $msg['state'] = 1;
                    $count = Db::table('address')->where('uid', $uid)->count();
                    if ($count == 0) {
                        $data['def'] = 1;
                    }
                    $address_id = Db::table('address')->insertGetId($data);
                    $msg['msg'] = '添加成功';
                }
            } else {
                $msg['state'] = 1;
                $msg['msg'] = '添加成功';
                Db::table('address')->where(['uid' => $uid, 'id' => $address_id])->update($data);
            }
            if ($msg['state'] == 1){
                if ($def == 1) {
                    Db::table('address')->where(['uid' => $uid])->update(['def' => 0]);
                    Db::table('address')->where(['uid' => $uid, 'id' => $address_id])->update(['def' => 1]);
                }
            }
        }
        return json($msg);
    }

    //删除地址
    public function del_address()
    {
        $uid = token_decode(req('token'));
        $address_id = req('address_id');
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($uid) || empty($address_id)) {
            $msg['msg'] = '参数错误';
        } else {
            $msg['state'] = 1;
            $check = Db::table('address')->where(['uid' => $uid, 'id' => $address_id])->find();
            if ($check['def'] == 1) {
                $next = Db::table('address')->where(['uid' => $uid, 'id' => ['<>', $check['id']]])->find();
                Db::table('address')->where(['uid' => $uid, 'id' => $next['id']])->update(['def' => 1]);
            }
            Db::table('address')->where(['uid' => $uid, 'id' => $address_id])->delete();
            $msg['msg'] = '操作成功';
        }
        return json($msg);
    }

    //获得我的红包列表
    public function red_packet_list()
    {
        $uid = token_decode(req('token'));
        $msg['state'] = 0;
        $msg['data'] = [];
        if (empty($uid)) {
            $msg['msg'] = '请登录后查看';
        } else {
            $msg['state'] = 1;
            $data = Db::table('red_packet')->field('id as red_id,seller_id,title,intime,full,minus,end_time,description')->where(['uid' => $uid, 'flag' => 0, 'end_time' => ['gt', time()]])->select();
            foreach ($data as $k => $v) {
                if ($v['seller_id'] == '') {
                    $seller_name = '全部商家可用';
                } else {
                    $seller_array = explode(',', $v['seller_id']);
                    $count_seller = count($seller_array);
                    $seller_name = '仅限';
                    if ($count_seller > 5) {
                        $seller_name = '部分商家可用';
                    } else {
                        foreach ($seller_array as $item) {
                            if ($item){
                                $seller_name .= Db::table('seller')->where('id', $item)->value('name') . ' ';
                            }
                        }
                        $seller_name .= '可用';
                    }
                }
                $data[$k]['seller_name'] = $seller_name;
            }
            $msg['data'] = $data;
            $msg['msg'] = '获取成功';
        }
        return json($msg);
    }

    //获取我的订单列表
    public function get_order_list()
    {
        $uid = token_decode(req('token'));
        $msg['state'] = 0;
        $msg['data'] = [];
        if (empty($uid)) {
            $msg['msg'] = '参数错误';
        } else {
            $msg['state'] = 1;
            $where['uid'] = $uid;
            $fields = 'order_id,title,lng,lat,address,name,phone,remark,seller_id,last_price,express_charge,sum_price,new_user_reduction,money_off_text,money_off,red_packet,status,advance,advance_receive,payment,time,pay_time,express_receive_time,seller_receive_time,express_time,complete_time,back_time,cancel_time,express_id';
            $page = !empty(req('page')) ? req('page') : 1;
            $page_size = !empty(req('page_size')) ? req('page_size') : 10;
            $msg['data'] = Db::table('order')->field($fields)->where($where)->page($page, $page_size)->order('time desc')->select();
            foreach ($msg['data'] as $k => $v) {
                $seller = Db::table('seller')->where('id', $v['seller_id'])->find();
                $msg['data'][$k]['seller_name'] = $seller['name'];
                $msg['data'][$k]['seller_headimg'] = $seller['headimg'];
                $msg['data'][$k]['seller_business'] = $seller['business'];
                $msg['data'][$k]['seller_advance'] = $seller['advance'];
                $msg['data'][$k]['seller_label'] = $seller['label'];
                $msg['data'][$k]['seller_lng'] = $seller['lng'];
                $msg['data'][$k]['seller_lat'] = $seller['lat'];
                $goods_total = 0;
                $goods_price = 0;
                $box_charge = 0;
                $goods = Db::table('order_detail')->field('title,image,service,price,number,price,box_charge')->where('order_id', $v['order_id'])->select();
                foreach ($goods as $gk => $gv) {
                    //$service = Db::table('service')->where('id', $gv['goods_id'])->find();
                    // $goods[$gk]['title'] = $service['title'];
                    // $goods[$gk]['image'] = $service['image1'];
                    // $goods[$gk]['service'] = $service['service'];
                    // $goods[$gk]['price'] = $service['price'];
                    $goods_total += $gv['number'];
                    $goods_price += $gv['number'] * $gv['price'];
                    $box_charge += $gv['number'] * $gv['box_charge'];
                    unset($goods[$gk]['box_charge']);
                }
                $msg['data'][$k]['goods_total'] = (string)$goods_total;
                $msg['data'][$k]['goods_price'] = (string)$goods_price;
                $msg['data'][$k]['goods_price'] = (string)$goods_price;
                $msg['data'][$k]['box_charge'] = (string)$box_charge;

                //是否评价
                $msg['data'][$k]['evaluate'] = Db::table('evaluate')->where(['order_id'=>$v['order_id'],'uid'=>$uid])->where(function ($query) {$query->where('time','>','complete_time')->whereor('complete_time','<',time() - 1296000);})->count();
				
				// $msg['data'][$k]['evaluate'] = Db::table('evaluate')->where('order_id = '.$v['order_id'].' AND uid = '.$uid.' AND time>complete_time or time<' . time() - 1296000)->count();
				// echo Db::table('evaluate')->getLastSql();exit;

                if (!empty($v['express_id'])) {
                    $express = Db::table('express')->where('id', $v['express_id'])->find();
                    $msg['data'][$k]['express_headimg'] = $express['headimg'];
                    $msg['data'][$k]['express_phone'] = $express['phone'];
                    $msg['data'][$k]['express_name'] = $express['name'];
                    $msg['data'][$k]['express_lng'] = $express['lng'];
                    $msg['data'][$k]['express_lat'] = $express['lat'];
                } else {
                    $msg['data'][$k]['express_headimg'] = '';
                    $msg['data'][$k]['express_phone'] = '';
                    $msg['data'][$k]['express_name'] = '';
                    $msg['data'][$k]['express_lng'] = '';
                    $msg['data'][$k]['express_lat'] = '';
                }
                $msg['data'][$k]['goods'] = $goods;
            }
            $msg['msg'] = '获取成功';
        }
        return json($msg);
    }

    //取消订单
    public function cancel_order()
    {
        $uid = token_decode(req('token'));
        $order_id = req('order_id');
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($uid) || empty($order_id)){
            $msg['msg'] = '参数错误';
        } else {
            $order = Db::table('order')->where(['order_id' => $order_id])->find();
            if (!empty($order['advance_receive']) || !empty($order['express_id'])) {
                $msg['msg'] = '配送员或商家已接单无法取消';
            } else{
                if ($order['status'] > 1) {
									//获取配送方式
									$iscancel = true;
									$express_type = Db::table("setting")->where(['id'=>1])->value('express_type');
									if($express_type == 1){
										vendor('dadaps.Dadaps#Api');
										$dadaApi = new \DadapsApi;
										$params['order_id'] = $order_id;
										$result = $dadaApi->CancelOrder($params);
										if($result['status'] == 1){
											$iscancel = true;
										}else{
											$iscancel = false;
										}
									}
									if($iscancel){
                                   //退款功能
										Db::table('order')->where(['uid' => $uid, 'order_id' => $order_id])->update(['status' => 5]);
                                        if ($order['payment'] == 'wxpay') {
											$pay_bool = false;
											//微信
											vendor('wxpayv_app.WxPay#Api');
											$input = new \WxPayRefund();
											$mchid = \WxPayConfig::$mchid;
											$input->SetOut_trade_no($order['order_id']);         //自己的订单号
											$input->SetTransaction_id(null);     //微信官方生成的订单流水号，在支付成功中有返回
											$input->SetOut_refund_no($order['order_id'] . '_exit');         //退款单号
											$input->SetTotal_fee($order['last_price'] * 100);         //订单标价金额，单位为分
											$input->SetRefund_fee($order['last_price'] * 100);            //退款总金额，订单总金额，单位为分，只能为整数
											$input->SetOp_user_id($mchid);
											$info = \WxPayApi::refund($input);
											if ($info['return_code'] == 'SUCCESS') {
													//退款申请成功
													$pay_bool = true;
													$msg['state'] = 1;
													$msg['msg'] = '操作成功';
											} else {
													//失败
													$msg['msg'] = '系统繁忙';
											}
											if($pay_bool){
													$msg['state'] = 1;
													//取消订单，退还优惠券
													Db::table('order')->where(['uid' => $uid, 'order_id' => $order_id])->update(['status' => 6, 'cancel_time' => time()]);
													if (!empty($order['red_id'])) {
															Db::table('red_packet')->where(['uid' => $uid, 'id' => $order['red_id']])->setDec('flag');
													}
													$msg['msg'] = '已成功取消订单';
											}
                    }else{
											$pay_bool = false;
											//alipay退款
											$this->alipay_config = Db::table("payment")->find();
											vendor('alipay.AopSdk');
											$aop = new \AopClient ();
											$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
											$aop->appId = $this->alipay_config['app_id'];
											$aop->rsaPrivateKey = $this->alipay_config['privatekey'];
											$aop->alipayrsaPublicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB';
											$aop->apiVersion = '1.0';
											$aop->signType = 'RSA';
											$aop->postCharset = 'utf-8';
											$aop->format = 'json';
											vendor('alipay.aop.request.AlipayTradeRefundRequest');
											$request = new \AlipayTradeRefundRequest();
											$request->setBizContent("{" .
													"    \"out_trade_no\":\"" . $order_id . "\"," .
													"    \"trade_no\":\"\"," .
													"    \"refund_amount\":\"" . $order['last_price'] . "\"," .
													"    \"refund_reason\":\"途骑退款\"," .
													"    \"out_request_no\":\"" . $order_id . "\"," .
													"    \"operator_id\":\"\"," .
													"    \"store_id\":\"\"," .
													"    \"terminal_id\":\"\"" .
													"}");
											$result = $aop->execute($request);
											$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
											$resultCode = $result->$responseNode->code;
			
											if (!empty($resultCode) && $resultCode == 10000) {
													if ($result->$responseNode->msg == "Success" && $result->$responseNode->refund_fee == $order['last_price']) {
															//退款申请成功
															$pay_bool = true;
															$msg['state'] = 1;
															$msg['msg'] = '操作成功';
													}
											} else {
													$msg['msg'] = '系统繁忙';
											}
											if($pay_bool){
													$msg['state'] = 1;
													//取消订单，退还优惠券
													Db::table('order')->where(['uid' => $uid, 'order_id' => $order_id])->update(['status' => 6, 'cancel_time' => time()]);
													if (!empty($order['red_id'])) {
															Db::table('red_packet')->where(['uid' => $uid, 'id' => $order['red_id']])->setDec('flag');
													}
													$msg['msg'] = '已成功取消订单';
											}else{
												Db::table('order')->where(['uid' => $uid, 'order_id' => $order_id])->update(['status' => $order['status']]);
											}
                    }
									}else{
										$msg['state'] = 0;
										$msg['msg'] = '系统繁忙，请稍后再试';
									}
                } else {
                    $msg['state'] = 1;
                    //取消订单，退还优惠券
                    Db::table('order')->where(['uid' => $uid, 'order_id' => $order_id])->update(['status' => 7, 'cancel_time' => time()]);
                    if (!empty($order['red_id'])) {
                        Db::table('red_packet')->where(['uid' => $uid, 'id' => $order['red_id']])->setDec('flag');
                    }
                    $msg['msg'] = '已成功取消订单';
                }
            }
        }
        return json($msg);
    }

    //再来一单
    public function order_again()
    {
        $uid = token_decode(req('token'));
        $order_id = req('order_id');
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($uid) || empty($order_id)){
            $msg['msg'] = '参数错误';
        } else{
            $msg['state'] = 1;
            $order = Db::table('order')->where(['order_id' => $order_id, 'uid' => $uid])->find();
            $cart_list = Db::table('cart')->field('uid,seller_id,goods_id,number,spec')->view('service','id as goods_id','cart.goods_id = service.id')->where(['cart.order_id' => $order_id, 'cart.seller_id' => $order['seller_id'], 'cart.uid' => $uid,'service.status'=>1,'service.flag'=>0])->select();
            // Db::table('cart')->where(['order_id' => '', 'seller_id' => $order['seller_id'], 'uid' => $uid])->delete();
            Db::table('cart')->insertAll($cart_list);
            $msg['msg'] = '操作完成';
        }
        return json($msg);
    }

    //用户订单评价
    public function order_evaluate()
    {
        $uid = token_decode(req('token'));
        $order_id = req('order_id');
        $type = req('type');
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($uid) || empty($order_id) || empty($type)) {
            $msg['msg'] = '参数错误';
        } else {
            // $count = Db::table('evaluate')->where(['order_id'=>$order_id,'uid'=>$uid,'type'=>$type])->where('time>complete_time or complete_time<=' . time() - 1296000)->count();
			 //是否评价
	   $count = Db::table('evaluate')->where(['order_id'=>$order_id,'uid'=>$uid,'type'=>$type])->where(function ($query){$query->where('time','>','complete_time')->whereor('complete_time','<',time() - 1296000);})->count();
            if($count == 0){
                $msg['state'] = 1;
                $data = [];
                $data['star'] = (string)req('star');
                $data['text'] = (string)req('text');
                $data['uid'] = $uid;
                $data['order_id'] = $order_id;
                $data['type'] = $type;
                if($type == 'seller'){
                    $data['seller_id'] = Db::table('order')->where('order_id',$order_id)->value('seller_id');
                }elseif ($type == 'express'){
                    $data['express_id'] = Db::table('order')->where('order_id',$order_id)->value('express_id');
                }
                if($_FILES){
                    $files = upload();
                    foreach ($_FILES as $index => $FILE) {
                        $data[$index] = $files[$index]['url'];
                    }
                }
                $data['time'] = time();
                Db::table('evaluate')->where(['order_id'=>$order_id,'uid'=>$uid,'type'=>$type])->delete();
                Db::table('evaluate')->insert($data);
                $msg['msg'] = '操作完成';
            }else{
                $msg['msg'] = '您已经评价过了哦~';
            }
        }
        return json($msg);
    }
    //用户分享订单
    public function order_share()
    {
        $uid = token_decode(req('token'));
        $order_id = req('order_id');
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($uid) || empty($order_id)) {
            $msg['msg'] = '参数错误';
        } else {
            // $count = Db::table('evaluate')->where(['order_id'=>$order_id,'uid'=>$uid,'type'=>$type])->where('time>complete_time or complete_time<=' . time() - 1296000)->count();
			 //是否评价
			$order = Db::table('order')->where(['order_id'=>$order_id])->where(['share'=>0])->field('pid,cid,aid')->find();
            if($order){
				$where['pid'] = $order['pid'];
				$where['cid'] = $order['cid'];
				$where['aid'] = $order['aid'];
				$where['status'] = 1;
				$where['title'] = '分享订单';
				$active = Db::table('active')->where($where)->find();
				if (!empty($active['json'])){
					$json_obj = json_decode($active['json']);
					foreach ($json_obj as $v){
						if ($v->minus){
							Db::table('red_packet')->insert(['uid' => $uid, 'full' => $v->full, 'minus' => $v->minus, 'end_time' => $this_time + ($v->indate * 86400), 'description' => '分享订单', 'flag' => 0]);
						}
					}
				}
                $msg['state'] = 1;
                $msg['msg'] = '操作完成';
            }else{
                $msg['msg'] = '您已经分享过了哦~';
            }
        }
        return json($msg);
    }
	
    //用户签到 order_sign
    public function order_sign()
    {
        $uid = token_decode(req('token'));
        $order_id = req('order_id');
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($uid)){
            $msg['msg'] = '参数错误';
        } else {
			$time = strtotime(date('Y-m-d'));
			$sign = Db::table('sign')->where(['uid'=>$uid])->where(['time'=>['>',$time]])->find();
			$score = Db::table("user_setting")->where(['id'=>1])->value('score');
            if(!$sign){
				$insert = array(
					'uid' => $uid,
					'score' => $score,
					'time' => time(),
				);
				Db::table('sign')->insert($insert);
				Db::table('user')->where(['uid'=>$uid])->setInc('score',$score);
                $msg['state'] = 1;
                $msg['msg'] = '操作完成';
            }else{
                $msg['msg'] = '您今天已经签到过了哦~';
            }
        }
        return json($msg);
    }
	
    //获取用户签到记录
    public function get_sing_record()
    {
        $uid = token_decode(req('token'));
        $order_id = req('order_id');
        $page = req('page')?req('page'):1;
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($uid)) {
            $msg['msg'] = '参数错误';
        } else {
			$msg['data'] = Db::table('sign')->where(['uid'=>$uid])->page($page,20)->select();
			$msg['state'] = 1;
			$msg['msg'] = '操作完成';
        }
        return json($msg);
    }
	//用户进行充值
     public function user_to_balance()
    {
	   $token=req('token');
	   $data['uid']=token_decode($token);
	   $data['balance']=req('balance');//余额
	   $data['province']=req('province');//省
	   $data['city']=req('city');//市
	   $data['area']=req('area');//县
	   $bool = true;
          foreach ($data as $k => $v){
           if ($v == '') {
                 $bool = false;
                 $msg['state']=0;
                 $msg['data']="";
                 $msg['msg'] = $k . '不能为空';
                 break;
              }
         }
	//if bool==true
        if($bool){
	      $area = Db::table('area')->where('name', 'like', '%' . $data['area'] . '%')->find();
               unset($data['area']);
              if ($area['status'] == 0){
				  $msg['state']=0;
                  $msg['msg'] = '抱歉，您所在的城市暂未开通服务';
               }else{
	         //城市未开通服务不可充值	   
		$msg['state']=1;
                $data['created_at']=time();//充值订单生成时间
                $data['pid'] = Db::table('province')->where('name', 'like', '%' . $data['province'] . '%')->value('id');
                unset($data['province']);
                $data['cid'] = Db::table('city')->where('name', 'like', '%' . $data['city'] . '%')->value('id');
                unset($data['city']);
                $data['aid'] = $area['id'];				
		$IDENT="UTB";
		$data['balance_id']=$IDENT.date('ymd').rand(1111,9999);
		$data['status']=1;//待充值
		$id=Db::table('user_balance')->insertGetId($data);
		$balance=Db::table('user_balance')->field('balance_id,balance,uid,status')->where('id',$id)->find();
	        //待支付['推送']
		if($balance['status']==1){
		  $IDENT = substr($balance['balance_id'], 0, 3);
                  $new_id = $IDENT . date('ymd') .rand(1111, 9999);
                  Db::table('user_balance')->where('balance_id', $balance['balance_id'])->update(['balance_id' =>$new_id]);
                  $balance['balance_id'] = $new_id;//微信支付时要更新id
		  $data=$this->balance_wxpay($balance);//微信支付
		  $data['balance_id']=$balance['balance_id'];//充值特有id
		  $data['balance']=$balance['balance'];//充值金额
		  $msg['data']=$data;
		  $msg['msg']="success";
		                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     }   
	        }
	    }
       return json($msg); 	
      }
   //获取用户充值信息
   public function get_user_balance()
   {
	  $token=req('token');
	  $uid=token_decode($token);
	  $balance_id=req('balance_id');
	  $type=req('type');
	  if(empty($uid)||empty($balance_id)){
		  $msg['state']=0;
		  $msg['msg']="数据出错";
		  $msg['data']=(object)[];
	   }else{
	     if($type=="balance_wxpay"){
		 $balance=Db::table("user_balance")->field('balance_id,balance,status')->where('balance_id',$balance_id)->find();
		 if($balance['status']==1){
		  $IDENT = substr($balance['balance_id'], 0, 3);
                  $new_id = $IDENT . date('ymd') .rand(1111, 9999);
                  Db::table('user_balance')->where('balance_id', $balance['balance_id'])->update(['balance_id' =>$new_id]);
                  $balance['balance_id'] = $new_id;//微信支付时要更新id
		  $data=$this->balance_wxpay($balance);//微信支付
	          $data['balance_id']=$balance['balance_id'];//充值特有id
		  $data['balance']=$balance['balance'];//充值金额
	          $msg['data']=$data;
		  $msg['msg']="success";
		   }
		  }elseif($type=="balance_alipay"){
			 $balance=Db::table("user_balance")->field("balance_id,balance,status")->where('balance_id',$balance_id)->find();
			 if($balance['status']==1){
				$msg['state']=1;
                                $msg['data']=$balance['balance'];
				$msg['msg']="success";
			 }
		  }
	  }
	 return json($msg);  
   }
    // 对签名字符串转义
    private function createLinkstring($para)
    {
        $arg = '';
        while (list($key, $val) = each($para)) {
            $arg .= $key . '="' . $val . '"&';
        }
        //去掉最后一个&字符
        $arg = substr($arg, 0, count($arg) - 2);
        //如果存在转义字符，那么去掉转义
        if (get_magic_quotes_gpc()) {
            $arg = stripslashes($arg);
        }
        return $arg;
    }

    // 签名生成订单信息
    private function rsaSign($data)
    {
        $priKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($this->alipay_config['privatekey'], 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        $res = openssl_get_privatekey($priKey);
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);
        $sign = base64_encode($sign);
        $sign = urlencode($sign);
        return $sign;
    }
   //用支付宝支付
   public function balance_alipay($data)
   {
	$this->alipay_config=Db::table("payment")->find();
	$partner=$this->alipay_config['partner'];//支付宝合作者身份id
	$seller_id=$this->alipay_config['seller_id'];//支付宝账户
	$balance_pay=$data['balance'];//要支付的金额
	 // 订单详情
    $body = '阳光外卖';
    $parameter = array(
            'service' => 'mobile.securitypay.pay',   // 必填，接口名称，固定值
            'partner' => $partner,                   // 必填，合作商户号
            '_input_charset' => 'UTF-8',                    // 必填，参数编码字符集
            'out_trade_no' => $data['balance_id'],          // 必填，商户网站唯一订单号
            'subject' => "发布订单：" .$body,           // 必填，商品名称
            'payment_type' => '1',                        // 必填，支付类型
            //'trade_no'   => $data['orderid'],
            'seller_id' => $seller_id,                 // 必填，卖家支付宝账号
            'total_fee' =>$balance_pay,             // 必填，总金额，取值范围为[0.01,100000000.00]
            'body' => $body,                      // 必填，商品详情
        );
	 // 
        //生成需要签名的订单
        $balanceInfo = $this->createLinkstring($parameter);
        //签名
        $sign = $this->rsaSign($balanceInfo);
        //生成订单
        $json = $balanceInfo . '&sign="' . $sign . '"&sign_type="RSA"';
        return json($json);	 

   }
   //微信支付充值
   public function balance_wxpay($data)
   {
        vendor('wxpayv_app.WxPay#Api');
        //订单详情
        $body = '阳光外卖';
        $url = \think\Url::build('wx_call_back', 'token=' . request()->request('token') . '&balance_id=' . $data['balance_id'], true, true);
        $unifiedOrder = new \WxPayUnifiedOrder();
        $unifiedOrder->SetBody($body);
        $unifiedOrder->SetOut_trade_no($data['balance_id']);
        $unifiedOrder->SetTotal_fee($data['balance'] * 100);
        $unifiedOrder->SetNotify_url($url);
        $unifiedOrder->SetTrade_type("APP");
        $result = \WxPayApi::unifiedOrder($unifiedOrder);
        return $result; 
   }
   //用户充值回调
    public function pay_balance_next()
    {
      $token=req('token');     
      $uid=token_decode($token);
      $balance_id=req("balance_id");
      $type=req("type");
      $balance=Db::table("user_balance")->where(['uid'=>$uid,'balance_id'=>$balance_id])->find();	
      $balance_pay=$balance['balance'];	
      if(empty($uid)||empty($balance_id)){
          $msg['state']=0;
          $msg['msg']="数据出错";
       }else{
          $pay_status=false;
          if($type=="balance_alipay"){
             $this->alipay_config = Db::table("payment")->find();//遍历数据库
             //引入alipay库
             vendor('alipay.AopSdk');
             $aop= new \AopClient();//实例化
             $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
             $aop->appId = $this->alipay_config['app_id'];
             $aop->rsaPrivateKey = $this->alipay_config['privatekey'];
             $aop->alipayPublicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCoTxq0aLilLpmrFG1SJyWkRoZ8ByzVercJhNM/Pdts3EDcIqCP7QU+utwzpzUza20LiVNihw6IcGyG8WYCkVOkOeX9frCCsthlQMLPNBhJg2sc483Fs5iSNTVNDF/0e+d/IOwAOFeK9zPkzP5px2HaR8w4SlIli+hIziRqkslBuwIDAQAB";
             $aop->apiVersion = '1.0';
             $aop->signType = 'RSA';//加密方法
             $aop->postCharset = 'utf-8';
             $aop->format = 'json';
             vendor('alipay.aop.request.AlipayTradeQueryRequest');//引入网关文件
                $request = new \AlipayTradeQueryRequest ();
                $request->setBizContent("{" .
                    "    \"out_trade_no\":\"" . $balance_id . "\"," .
                    "    \"trade_no\":\"\"" .
                    "  }");
                //设置订单号 out_trade_no 用户充值订单
                $result = $aop->execute($request);
                $responseNode = str_replace(".", "_", $request->getApiMethodName())."_response";
                $resultCode = $result->$responseNode->code;
                if(!empty($resultCode) && $resultCode =='10000'){
                   if($result->$responseNode->trade_status == "TRADE_SUCCESS" && $result->$responseNode->total_amount==(string)$balance_pay){
                        $pay_status = true;                                                               //订单中的价格[计算后的]
                        $msg['state'] = 1;
                        $msg['msg'] = '支付成功';
                    }else{
                        $pay_status = false;
                        $msg['state']=0;
                        $msg['msg'] = '支付失败';
                    }
                 }else{
                    $msg['state']=0;
                    $msg['data']='';
                    $msg['msg'] = '支付失败';
                 } 
          }elseif($type=="balance_wxpay"){
                 vendor('wxpayv_app.WxPay#Api');
                 $input = new \WxPayOrderQuery();
                 $input->SetOut_trade_no($balance_id);
                 $result = \WxPayApi::orderQuery($input);
                 //var_dump($result);exit;
               if($result['result_code'] == "SUCCESS"){
                    if($result['trade_state'] == "SUCCESS" && $result['total_fee']==(string)$balance_pay* 100){
                        $pay_status = true;                                                
                        $msg['state'] = 1;
                        $msg['msg'] = '支付成功';
                    }else{
                        $msg['msg'] = '支付失败';
                        $pay_status = false;
                    }
                } 
              
          }
         //支付成功
          if($pay_status){
              $balance=Db::table("user_balance")->where(['balance_id'=>$balance_id])->find();
              $balance_money=$balance['balance'];//所要充值的金额
              Db::table('user_balance')->where(['balance_id'=>$balance_id])->update(['type'=>$type]);//更新充值类型
             //检测用户账户有没有账户余额若无就更新余额，有就自增
              $user_data=Db::table("user")->where(['id'=>$uid])->find();
              if(empty($user_data['balance'])){
                Db::table("user")->where(['id'=>$uid])->update(['balance'=>$balance_money]);
                Db::table('user')->where(['id'=>$uid])->setInc('score',$balance_money);
                Db::table("user_balance")->where(['balance_id'=>$balance_id])->update(['status'=>2]);//改变充值订单状态
              }else{
               Db::table('user')->where(['id'=>$uid])->setInc('balance',$balance_money);  
               Db::table('user')->where(['id'=>$uid])->setInc('score',$balance_money);
               Db::table("user_balance")->where(['balance_id'=>$balance_id])->update(['status'=>2]);//改变充值订单状态   
              }
          }
      }
 } 
 
 
 
 //抽奖页
 public function user_chou()
{
  
  return  view();   
 }
 public function lottery_json()
 {  
    $uid=2;
    $prizes=Db::table("chou_data")->field("id,name,count")->where(['status'=>1])->select();
    $i = 1;
    foreach ($prizes as $v){
        $proArr[$i] = $v['id'];//奖品id
        $proCount[$i] = $v['count']; //奖品库存动态
        $i++;
    }
    $data =[
        '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 0,
    ];
    $rid = $this->getRand($proArr, $proCount);
    
    if ($rid > 6){
        $rid = 0;
    } else{
        $rid = $this->returnRid($rid, $data, $proCount, $proArr);
    }
    $rname = "";
    foreach ($prizes as $v){
        if ($v['id'] == $rid){
            $rname = $v['name'];
            break;
        }
    } 
    //检验积分是否符合抽奖条件
    $fen=$this->user_is_fulled_fen($uid);
    
    //查询在一天内是否抽取三次 如果抽取三次则返回1,否则就返回0
    $re=$this->user_is_choued($uid);
    //查询所抽取的奖项库存是否充足
    // $ku=$this->user_data_ku_isfulled($rid);
    //抽取次数
    if($re!==1){
        //生成抽奖记录
       $this->user_chou_register($uid,$rid,$rname);
        //并扣除相应的积分(score);
       $this->user_del_score($uid);
       //库存数充足则扣除相应的库存
     //  $this->user_del_ku($rid);
    }
    echo json_encode(array("rid" => $rid, "rname" => $rname,"re" =>$re,"fen"=>$fen));
 }
 public function returnRid($rid, $data, $proCount, $proArr){
    $data[$rid] = $data[$rid] + 1;
    $count = $proCount[$rid]; // 总库存
    if ($count < $data[$rid]) {
        // 如果抽取的数据大于总库存时库存清0
        $proCount[$rid] = 0;
        // 然后继续计算一直计算出某个值的库存不为0
        $rid = $this->returnRid($rid, $data, $proCount, $proArr);
    }
    return $rid;
}

/**
 * 中奖概率计算, 能用
 * $proArr = array('1'=>'概率', '2'=>'概率');
 * $proCount = array('1'=>'库存', '2'=>'库存');
 */
public function getRand($proArr, $proCount){
    $result = '';
    $proSum = 0;
    foreach ($proCount as $key => $val){
        if ($val <= 0) {
            continue;
        } else {
            $proSum = $proSum + $proArr[$key];
        }
    }
    foreach ($proArr as $key => $proCur) {
        if ($proCount[$key] <= 0) {
            continue;
        } else {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur){
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
    }
    unset($proArr);//库存
    return $result;
}
  //检查积分是否符合抽奖条件
  public function user_is_fulled_fen($uid)
  {
     $fer=Db::table("user")->where("id",$uid)->value("score");
     if($fer<=0){
       return 1;
     }else{
       return 0;
     }
        
  }
 //用户抽奖并生成生成抽奖记录
 public function user_chou_register($uid,$rid,$rname)
 {
   $data=[];
   $data['uid']=$uid;
   $data['rid']=$rid;
   $data['rname']=$rname;
   $data['date']=date('Y-m-d');
   $data['status']=1;
   $data['insert_time']=time();//时间戳
   //插入数据库
   Db::table("user_chou_record")->insert($data);  
 }
 
 //返回1 or 0;
 public function  user_is_choued($uid)
 {   //判断
     $date=date("Y-m-d");//当天时间
     $count=Db::table("user_chou_record")->where(["uid"=>$uid,'date'=>$date])->count();
     if($count>=3){
         return 1;
     }else{
         return 0;
     }
    
 }
 //每抽取一次 扣除一次user表中的积分
 public function user_del_score($uid)
 { 
     if(!empty($uid)){
        $score=Db::table("user")->where('id',$uid)->value("score"); 
        if($score<=0){
           Db::table("user")->where('id',$uid)->update(['score'=>0]); 
        }else{
           Db::table('user')->where('id',$uid)->setDec('score',1);
        }
     }
   
 }
 //判断库存是否充足:如果不充足则返回1 如果充足则返回0
 public function user_data_ku_isfulled($rid)
 {
    $ku=Db::table("chou_data")->where(['id'=>$rid,'status'=>1])->value("count");
    if($ku<=0){
       return 1; 
    }else{
       return 0;
    } 
 }
 //减少相应的库存
 public function user_del_ku($rid)
 {
    if(!empty($rid)){
        $count=Db::table("chou_data")->where(['id'=>$rid,'status'=>1])->value("count");
        if($count<=0){
            Db::table("chou_data")->where(['id'=>$rid,'status'=>1])->update(['count'=>0]); 
        }else{
           Db::table("chou_data")->where(['id'=>$rid,'status'=>1])->setDec("count",1);
        }
    }   
 }
 
 
 
 
 
 
 
 
}